<template>
  <div class="role-management-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-form-wrapper">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="角色名称">
            <el-input 
              v-model="searchForm.roleName" 
              placeholder="请输入角色名称" 
              clearable 
              style="width: 220px;"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item label="角色标识">
            <el-input 
              v-model="searchForm.roleKey" 
              placeholder="请输入角色标识" 
              clearable 
              style="width: 220px;"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleSearch"
              class="search-button"
              :icon="Search"
            >
              搜索
            </el-button>
            <el-button 
              @click="handleReset"
              :icon="Refresh"
            >
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add-button-wrapper">
        <el-button 
          type="primary" 
          @click="handleAddRole"
          class="add-role-btn"
          :icon="Plus"
        >
          添加角色
        </el-button>
      </div>
    </div>

    <!-- 角色列表表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="roles"
        style="width: 100%;"
        border
        fit
        @row-click="handleRowClick"
        empty-text="暂无数据"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="角色名称" min-width="180">
          <template #default="scope">
            <div class="role-name">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="label" label="角色标识" min-width="180">
          <template #default="scope">
            <div class="role-key">
              {{ scope.row.label || scope.row.roleKey }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" min-width="200">
          <template #default="scope">
            <div class="update-time">
              <el-tooltip :content="formatDateTime(scope.row.updateTime)" placement="top">
                <span>{{ formatDateTime(scope.row.updateTime) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
                :icon="Edit"
                class="edit-btn"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
                :icon="Delete"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        <el-icon><Document /></el-icon>
        <span>共 {{ totalCount }} 条记录</span>
      </div>
      <div class="pagination-controls">
          <el-select 
            v-model="pageSize" 
            @change="handleSizeChange" 
            style="width: 100px; margin-right: 15px;"
            size="small"
          >
            <el-option :label="'10条/页'" :value="10" />
            <el-option :label="'20条/页'" :value="20" />
            <el-option :label="'50条/页'" :value="50" />
          </el-select>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="prev, pager, next"
            :total="totalCount"
            @current-change="handleCurrentChange"
            background
            small
            hide-on-single-page
          />
      </div>
    </div>

    <!-- 添加角色对话框 -->
    <el-dialog 
      v-model="dialogVisible.add" 
      title="新增角色" 
      width="500px"
      destroy-on-close
    >
      <el-form 
        ref="addFormRef" 
        :model="addForm" 
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input v-model="addForm.roleKey" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="角色备注" prop="remark">
          <el-input 
            v-model="addForm.remark" 
            placeholder="请输入角色备注" 
            type="textarea" 
            rows="3"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.add = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog 
      v-model="dialogVisible.edit" 
      title="修改角色" 
      width="500px"
      destroy-on-close
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input v-model="editForm.roleKey" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="角色备注" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            placeholder="请输入角色备注" 
            type="textarea" 
            rows="3"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.edit = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="dialogVisible.delete"
      title="确认删除"
      width="400px"
      destroy-on-close
    >
      <p>确定要删除角色「{{ deleteForm.name }}」吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.delete = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteConfirm">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  Document 
} from '@element-plus/icons-vue'
import { getRoleList, addRole, updateRole, deleteRole } from '@/api/role'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleKey: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const roles = ref([])
const loading = ref(false)

// 对话框可见性
const dialogVisible = reactive({
  add: false,
  edit: false,
  delete: false
})

// 添加表单
const addForm = reactive({
  name: '',
  roleKey: '',
  remark: ''
})
const addFormRef = ref(null)

// 修改表单
const editForm = reactive({
  id: '',
  name: '',
  roleKey: '',
  remark: ''
})
const editFormRef = ref(null)

// 删除表单
const deleteForm = reactive({
  id: '',
  name: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 10, message: '角色名称长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 20, message: '角色标识长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '角色标识只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  remark: [
    { max: 50, message: '角色备注最多50个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '--'
  return dateTime
}

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.roleName,
      roleKey: searchForm.roleKey
    }
    
    const response = await getRoleList(params)
    if (response && response.data) {
      // 根据最后修改时间倒序排列
      roles.value = (response.data.rows || []).sort((a, b) => {
        return new Date(b.updateTime || 0) - new Date(a.updateTime || 0)
      })
      totalCount.value = response.data.total || 0
    } else {
      roles.value = []
      totalCount.value = 0
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    roles.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadRoles()
}

// 清空搜索
const handleReset = () => {
  searchForm.roleName = ''
  searchForm.roleKey = ''
  currentPage.value = 1
  loadRoles()
}

// 显示添加角色对话框
const handleAddRole = () => {
  addForm.name = ''
  addForm.roleKey = ''
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  dialogVisible.add = true
}

// 处理添加确认
const handleAddConfirm = async () => {
  if (addFormRef.value) {
    await addFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const roleData = {
            name: addForm.name,
            roleKey: addForm.roleKey,
            remark: addForm.remark
          }
          
          await addRole(roleData)
          dialogVisible.add = false
          ElMessage.success('添加成功')
          currentPage.value = 1
          loadRoles() // 重新加载数据
        } catch (error) {
          console.error('添加角色失败:', error)
          // 错误信息已在响应拦截器中处理
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 显示修改角色对话框
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.roleKey = row.label || row.roleKey // 兼容后端返回的label字段
  editForm.remark = row.remark || ''
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  dialogVisible.edit = true
}

// 处理修改确认
const handleEditConfirm = async () => {
  if (editFormRef.value) {
    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const roleData = {
            id: editForm.id,
            name: editForm.name,
            roleKey: editForm.roleKey,
            remark: editForm.remark
          }
          
          await updateRole(roleData)
          dialogVisible.edit = false
          ElMessage.success('修改成功')
          loadRoles() // 重新加载数据
        } catch (error) {
          console.error('修改角色失败:', error)
          // 错误信息已在响应拦截器中处理
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 显示删除确认对话框
const handleDelete = (row) => {
  deleteForm.id = row.id
  deleteForm.name = row.name
  dialogVisible.delete = true
}

// 处理删除确认
const handleDeleteConfirm = async () => {
  loading.value = true
  try {
    await deleteRole(deleteForm.id)
    dialogVisible.delete = false
    ElMessage.success('删除成功')
    // 检查是否需要调整页码
    if (roles.value.length === 1 && currentPage.value > 1) {
      currentPage.value--
    }
    loadRoles() // 重新加载数据
  } catch (error) {
    console.error('删除角色失败:', error)
    // 检查是否是角色正在被使用的错误
    if (error.response && error.response.data && error.response.data.message && 
        error.response.data.message.includes('正在被使用')) {
      // 错误信息已在响应拦截器中处理，这里不需要额外处理
    }
    // 其他错误也已在响应拦截器中处理
  } finally {
    loading.value = false
  }
}

// 处理行点击
const handleRowClick = (row, event, column) => {
  // 可以在这里添加行点击事件处理
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadRoles()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadRoles()
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.role-management-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.search-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-form-wrapper {
  flex: 1;
  min-width: 500px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-button {
  transition: all 0.3s ease;
}

.search-button:hover {
  transform: translateY(-1px);
}

.add-button-wrapper {
  display: flex;
  justify-content: flex-end;
}

.add-role-btn {
  transition: all 0.3s ease;
  font-weight: 500;
  padding: 8px 20px;
}

.add-role-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(48, 164, 255, 0.3);
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

/* 角色名称和标识样式 */
.role-name,
.role-key {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 更新时间样式 */
.update-time {
  font-size: 13px;
  color: #606266;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.edit-btn,
.delete-btn {
  transition: all 0.3s ease;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(48, 164, 255, 0.3);
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(233, 30, 99, 0.3);
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 加载动画样式 */
:deep(.el-loading-spinner .path) {
  stroke: #409eff;
}

:deep(.el-loading-spinner .el-loading-text) {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .role-management-container {
    padding: 15px;
  }
  
  .search-area {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-form-wrapper {
    min-width: 100%;
  }
  
  .add-button-wrapper {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .role-management-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>